/**
 * 
 * @param {Object} json 数组类型的数据
 * @param {Object} opt opt.type 1,2 ,3单列,两列联动，两列不联动,opt.target 容器id，每条高度：opt.itemHeight, 点击确定，取消的事件:opt.okEvent,opt.cancelEvent
 */
;(function linkStyle(){
	var scriptArr =  Array.prototype.slice.call(document.scripts);
	var reg = /picker\.js/;//只允许有一个文件名为picker.js的插件，否则可能会错误加载css文件
	var targetArr = scriptArr.filter(function(item){
		if((item.src)&&(reg.test(item.src))){
			return item;
		};
	});
	var target = targetArr[0].src;
	var basePath = target.substring(0,(target.lastIndexOf('/')+1));
	var cssPath = basePath + '/css/picker.css';
	var linkNode = document.createElement('link');
	linkNode.rel = 'stylesheet';
	linkNode.href = cssPath;
	document.head.appendChild(linkNode);
}());
function lcPicker(json,opt){
//	this.linkStyle();
	this.listData = json;
	this.opt = opt;
	this.opt.title = this.opt.title || '选择器';
	this.opt.name = this.opt.name || 'name';
	this.opt.value = this.opt.value || 'value';
	this.opt.child = this.opt.child || 'child';
	this.opt.parent = this.opt.parent || 'parent';
	this.moveParam = {}; //和移动相关的参数
	this.type  = opt.type ? opt.type : 1;
	this.itemHeight = opt.itemHeight ? opt.itemHeight : 30; //每条的高度，默认是30
	this.init();
};
//初始化
lcPicker.prototype.init = function(){
	var target = document.getElementById(this.opt.target);
	if(!target){
		var mask = document.createElement('div');
		mask.id = 'pic-mask';
		mask.className = 'pic-mask';
		document.body.appendChild(mask);
		target = document.createElement('div');
		target.id = this.opt.target;
		target.className = 'pic-container';
		mask.appendChild(target);
	};
	this.target = target;
	this.createFrame(this.type);
	this.addListener();
};
//装填框架html生
lcPicker.prototype.createFrame = function (flag){
	var html = '';
	if(flag == 1){ //单列
		html = '<div class="lpic-play"><p class="pic-title">'+this.opt.title+'</p><div class="lpicker-con"><div class="d-con">'+
				'<div class="left-select" style="text-align:center;padding-right:0;"></div></div>'+
				'<div class="p-center"></div></div><div class="select-btn-row">'+
				'<a href="javascript:void(0)" class="pic-cancel">取消</a>'+
				'<a href="javascript:void(0)" class="pic-ok">确定</a>'+
				'</div></div>';
	}else if((flag == 2) ||(flag == 3)){//双列
		html = '<div class="lpic-play"><p class="pic-title">'+this.opt.title+'</p><div class="lpicker-con"><div class="d-con">'+
				'<div class="left-select"></div><div class="right-select"></div></div>'+
				'<div class="p-center"></div></div><div class="select-btn-row">'+
				'<a href="javascript:void(0)" class="pic-cancel">取消</a>'+
				'<a href="javascript:void(0)" class="pic-ok">确定</a>'+
				'</div></div>';
	}else if(flag == 4){ //三级城市联动
		html = '<div class="lpic-play"><p class="pic-title">'+this.opt.title+'</p><div class="lpicker-con"><div class="d-con">'+
				'<div class="left-select"></div><div class="center-select"></div><div class="right-select"></div></div>'+
				'<div class="p-center"></div></div><div class="select-btn-row">'+
				'<a href="javascript:void(0)" class="pic-cancel">取消</a>'+
				'<a href="javascript:void(0)" class="pic-ok">确定</a>'+
				'</div></div>';
	};
	this.target.innerHTML = html;
	this.target.getElementsByClassName('p-center')[0].style.height = this.itemHeight + 'px';
	this.picCon = this.target.getElementsByClassName('lpicker-con')[0];//舞台元素
	this.parentNode = this.picCon.getElementsByClassName('left-select')[0];
	this.opt.height = parseInt(window.getComputedStyle(this.picCon,'').height);//舞台height
	this.originY = Math.floor((this.opt.height - this.itemHeight)/2); //第一条数据居中的translate中y位置
	this.addParentData(0);//添加一级节点,默认选中0
	if((flag == 2) || (flag == 3)){ //类型2和3需要添加二级节点
		this.childNode = this.picCon.getElementsByClassName('right-select')[0];
		this.addChildData([0,0]);//默认选中[0,0]
	}else if(flag == 4){
		this.childNode = this.picCon.getElementsByClassName('center-select')[0];
		this.grandNode = this.picCon.getElementsByClassName('right-select')[0]
		this.addChildData([0,0]);//默认选中[0,0]
		this.addGranData([0,0,0]);
	};
//	console.log(this.opt.height);
};
/**
 * 装填父级节点
 * @param {Object} flag 选中标志位， 负数都不选中，0选中第一个
 */
lcPicker.prototype.addParentData = function(flag){
	var html = '';
	var dataName = this.opt.name;
	var dataValue = this.opt.value;
	var dataChild = this.opt.child;
	var listData = null;
	if((this.type == 1) || (this.type == 2)||(this.type == 4)){
		listData = this.listData;
	}else if(this.type == 3){
		listData = this.listData[this.opt.parent];
	};
	listData.forEach(function(value,item){
		html = html + '<p class="p-item" data-value="'+value[dataValue]+'">'+value[dataName]+'</p>';
	});
	this.parentNode.innerHTML = html;
	if((typeof flag) == 'number'){
		this.parentNode.style.webkitTransform = 'translate3d(0,'+(this.originY - flag*this.itemHeight)+'px,0)';
		this.parentNode.style.transform = 'translate3d(0,'+(this.originY - flag*this.itemHeight)+'px,0)';
	}else{
		flag = 0;
		this.parentNode.style.webkitTransform = 'translate3d(0,'+(this.originY - flag*this.itemHeight)+'px,0)';
		this.parentNode.style.transform = 'translate3d(0,'+(this.originY - flag*this.itemHeight)+'px,0)';
		this.moveParam.curPY = this.originY - flag*this.itemHeight;
	};
	this.moveParam.curPY = this.originY - flag*this.itemHeight; //父节点当前选中位置
	this.selectedPItem = flag;//当前选中父节点item的index;
	if(flag > -1){
		this.parentNode.getElementsByClassName('p-item')[flag].classList.add('pic-selected');	
	}
};
/**
 * 装填子节点
 * @param {Object} flag 选中标志位， -1都不选中，0选中第一个
 */
lcPicker.prototype.addChildData = function(flagArr){
	var listData = null;
	var dataName = this.opt.name;
	var dataValue = this.opt.value;
	var dataChild = this.opt.child;
	if((this.type == 2)||(this.type == 4)){
		listData = this.listData[flagArr[0]][dataChild];
	}else if(this.type == 3){
		listData = this.listData[dataChild];
	};
//	console.log(listData);
	var html = '';
	listData.forEach(function(value,item){
		html = html + '<p class="p-item" data-value="'+value[dataValue]+'">'+value[dataName]+'</p>';
	});
	this.childNode.innerHTML = html;
	this.childNode.style.webkitTransform = 'translate3d(0,'+(this.originY - flagArr[1]*this.itemHeight)+'px,0)';
	this.childNode.style.transform = 'translate3d(0,'+(this.originY - flagArr[1]*this.itemHeight)+'px,0)';
	if(flagArr[1] >-1){
		this.childNode.getElementsByClassName('p-item')[flagArr[1]].classList.add('pic-selected');
	};
	this.selectedCItem = flagArr[1];//当前选中子节点item的index;
	this.moveParam.curCY = this.originY - flagArr[1]*this.itemHeight; //子节点当前选中位置
};
lcPicker.prototype.addGranData = function(flagArr){//三级节点
	var listData = null;
	var dataName = this.opt.name;
	var dataValue = this.opt.value;
	var dataChild = this.opt.child;
	if(this.type == 4){
		var parentData = this.listData[flagArr[0]];
		var childData = parentData[dataChild][flagArr[1]];
		listData = childData[dataChild];
	};
	var html = '';
	listData.forEach(function(value,item){
		html = html + '<p class="p-item" data-value="'+value[dataValue]+'">'+value[dataName]+'</p>';
	});
	this.grandNode.innerHTML = html;
	this.grandNode.style.webkitTransform = 'translate3d(0,'+(this.originY - flagArr[2]*this.itemHeight)+'px,0)';
	this.grandNode.style.transform = 'translate3d(0,'+(this.originY - flagArr[2]*this.itemHeight)+'px,0)';
	this.grandNode.getElementsByClassName('p-item')[flagArr[2]].classList.add('pic-selected');
	this.selectedGItem = flagArr[2];//当前选中子节点item的index;
	this.moveParam.curGY = this.originY - flagArr[2]*this.itemHeight; //子节点当前选中位置
};
/**
 * 根据指定的value数组将选择的初始位置置于指定的位置
 * @param {Object} flagArr 查询的value组成的数组,一级['110'], 二级['110','11'],三级[110,34,23]
 */
lcPicker.prototype.setItem = function(flagArr){
	var dataName = this.opt.name;
	var dataValue = this.opt.value;
	var dataChild = this.opt.child;
	var locArr = [];
	if(this.type == 1){
		locArr[0] = locationItem(this.listData,flagArr[0]);
	}else if(this.type == 2){
		locArr[0] = locationItem(this.listData,flagArr[0]);
		var selParent = this.listData[locArr[0]];//被选中的1级节点
		locArr[1] = locationItem(selParent[dataChild],flagArr[1]);
	}else if(this.type == 3){
		locArr[0] = locationItem(this.listData[this.opt.parent],flagArr[0]);
		locArr[1] = locationItem(this.listData[dataChild],flagArr[1]);
	}else if(this.type == 4){
		locArr[0] = locationItem(this.listData,flagArr[0]);
		var selParent = this.listData[locArr[0]];//被选中的1级节点
		locArr[1] = locationItem(selParent[dataChild],flagArr[1]);//被选中的二级编号
		var selChild = selParent[dataChild][locArr[1]];//被选中的二级节点
//		console.log(selParent);
		console.log(selChild);
		locArr[2] = locationItem(selChild[dataChild],flagArr[2]);
	};
	for (var i = 0;i < locArr.length;i++) {
		if(locArr[i] < 0){
			break;
		}else{
			if(i == 0){
				this.setPCurItem(locArr[0]);
			}else if(i == 1){
				var arr = new Array();
				arr.push(locArr[0]);
				arr.push(locArr[1]);
				this.addChildData(arr);
//				this.setCCurItem(arr);
			}else if(i == 2){
//				this.setGCurItem(locArr);
				this.addGranData(locArr);
			};
		};
	};
	/**
	 * 根据对象的value进行数据定位
	 * @param {Object} locData 要被查询的数组
	 * @param {Object} flag 查询值
	 */
	function locationItem(locData,flag){
		var i = 0;
		for (i = 0;i < locData.length;i++) {
			if(locData[i][dataValue] == flag){
				return i;
			};
		};
		return -1;
	};
};
//设置监听事件
lcPicker.prototype.addListener = function(){
	var _this = this;
	var deviceWidth = document.documentElement.clientWidth || document.body.clientWidth;
	//touch处理函数
	var tochObj = { 
		touchStart:function(ev){
			var point = ev.changedTouches[0];
			ev.preventDefault();
			ev.stopPropagation();
			if((_this.type == 2) || (_this.type == 3)){
				if(point.clientX > Math.floor(deviceWidth/2)){
					_this.targetList = _this.childNode;
					_this.moveParam.curNode = 'curCY';//标志移动的是子节点，通过curCY可以获取初始子节点的y值,
					_this.moveParam.tempItem = _this.selectedCItem;//临时记录当前选中项
				}else{
					_this.targetList = _this.parentNode;
					_this.moveParam.curNode = 'curPY'; //标志移动的是父节点，通过curPY可以获取初始父节点的y值
					_this.moveParam.tempItem = _this.selectedPItem;//临时记录当前选中项
				};
			}else if(_this.type == 1){
				_this.targetList = _this.parentNode;
				_this.moveParam.curNode = 'curPY';//标志移动的是父节点，通过curPY可以获取初始父节点的y值
				_this.moveParam.tempItem = _this.selectedPItem;//临时记录当前选中项
			}else if(_this.type == 4){
				if(point.clientX < Math.floor(deviceWidth/3)){
					_this.targetList = _this.parentNode;
					_this.moveParam.curNode = 'curPY';//标志移动的是一级节点，通过curCY可以获取初始子节点的y值,
					_this.moveParam.tempItem = _this.selectedPItem;//临时记录当前选中项
//					console.log(_this.moveParam.curNode);
				}else if((point.clientX < Math.floor(deviceWidth/3)*2) && (point.clientX > Math.floor(deviceWidth/3))){
					_this.targetList = _this.childNode;
					_this.moveParam.curNode = 'curCY'; //标志移动的是父节点，通过curPY可以获取初始父节点的y值
					_this.moveParam.tempItem = _this.selectedCItem;//临时记录当前选中项
//					console.log(_this.moveParam.curNode);
				}else if(point.clientX > Math.floor(deviceWidth/3)*2){
					_this.targetList = _this.grandNode;
					_this.moveParam.curNode = 'curGY'; //标志移动的是三级节点，通过curPY可以获取初始父节点的y值
					_this.moveParam.tempItem = _this.selectedGItem;//临时记录当前选中项
				};
			};
			_this.moveParam.lastItem = _this.moveParam.tempItem; //上一条选中项，初始时等于当前选中项
			_this.moveParam.selectedItem = _this.moveParam.tempItem;
			_this.targetList.style.webkitTransitionDuration = '0s';
			_this.targetList.style.transitionDuration = '0s';
			_this.moveParam.startY = point.clientY; //开始拖动时，触点y值
			_this.moveY = 0;//y方向的移动拖动距离
			_this.moveParam.pointY = point.clientY; //y拖动取点
//			console.log(_this.moveParam);
		},
		touchMove:function(ev){
			ev.preventDefault();
			ev.stopPropagation();
			var movePoint = ev.changedTouches[0];
			var moveY = movePoint.clientY - _this.moveParam.startY;
			_this.moveY = moveY;
//			console.log(moveY,_this.moveParam[_this.moveParam.curNode]);
			_this.targetList.style.webkitTransform = 'translate3d(0,'+(_this.moveParam[_this.moveParam.curNode]+moveY)+'px,0)';
			_this.targetList.style.transform = 'translate3d(0,'+(_this.moveParam[_this.moveParam.curNode]+moveY)+'px,0)';
			var reMoveY = Math.abs(moveY) - Math.abs(_this.moveParam.tempItem - _this.moveParam.selectedItem)*_this.itemHeight;
//			console.log(_this.moveParam.tempItem,_this.moveParam.selectedItem);
			if(Math.abs(reMoveY) >= 30){
				if((movePoint.clientY - _this.moveParam.pointY) > 0){
//					console.log('--');
					_this.moveParam.lastItem = _this.moveParam.tempItem;
					_this.moveParam.tempItem--;
				}else if((movePoint.clientY - _this.moveParam.pointY) < 0){
					_this.moveParam.lastItem = _this.moveParam.tempItem;
					_this.moveParam.tempItem++;
//					console.log('++');
				}else{
					
				};
				_this.moveParam.pointY = movePoint.clientY;
				if((_this.moveParam.lastItem > -1)&&(_this.moveParam.lastItem < _this.targetList.getElementsByClassName('p-item').length)){
					try{
						var list = _this.targetList.getElementsByClassName('p-item');
						list[_this.moveParam.lastItem].className = 'p-item';
					}catch(e){
						console.error(e);
					};
				};
				if((_this.moveParam.tempItem > -1)&&(_this.moveParam.tempItem < _this.targetList.getElementsByClassName('p-item').length)){
					try{
						var list = _this.targetList.getElementsByClassName('p-item');
						list[_this.moveParam.tempItem].classList.add('pic-selected');
					}catch(e){
						console.error(e);
					};
				};
			};
//			console.log(reMoveY,_this.moveParam.tempItem);
		},
		touchEnd:function(ev){
			_this.targetList.style.webkitTransitionDuration = '300ms';
			_this.targetList.style.transitionDuration = '300ms';
			var endPoint = ev.changedTouches[0];
			var distancY = endPoint.clientY - _this.moveParam.startY;
			var moveItem = -Math.round(distancY/_this.itemHeight);
			if(_this.moveParam.curNode == 'curPY'){ //父节点变化
				
				var curItem = _this.selectedPItem + moveItem;
				var lastItem = _this.selectedPItem;
				if(curItem < 0 ){
					curItem = 0;
				}else if(curItem >= _this.targetList.getElementsByClassName('p-item').length){
					curItem = _this.targetList.getElementsByClassName('p-item').length -1;
				};
				_this.setPCurItem(curItem);
				if((_this.type == 2) && (curItem != lastItem)){ //二级联动类型，当父节点变化时需重新装填子节点
					_this.addChildData([curItem,0]);
				}else if((_this.type == 4) && (curItem != lastItem)){
					_this.addChildData([curItem,0]);
					_this.addGranData([curItem,_this.selectedCItem,0]);
				};
			}else if(_this.moveParam.curNode == 'curCY'){ //子节点变化
				var curItem = _this.selectedCItem + moveItem;
				if(curItem < 0 ){
					curItem = 0;
				}else if(curItem >= _this.targetList.getElementsByClassName('p-item').length){
					curItem = _this.targetList.getElementsByClassName('p-item').length -1;
				};
				_this.setCCurItem([_this.selectedPItem,curItem]);
				if((_this.type == 4) && (curItem != lastItem)){
					_this.addGranData([_this.selectedPItem,_this.selectedCItem,0]);
				};
			}else if(_this.moveParam.curNode == 'curGY'){ //三级节点变化
				var curItem = _this.selectedGItem + moveItem;
				if(curItem < 0 ){
					curItem = 0;
				}else if(curItem >= _this.targetList.getElementsByClassName('p-item').length){
					curItem = _this.targetList.getElementsByClassName('p-item').length -1;
				};
				_this.setGCurItem([_this.selectedPItem,_this.selectedCItem,curItem]);
			};
		},
		okEvent:function(ev){
			var result = {
				pValue:'',
				pName:'',
				cValue:'',
				cName:'',
				gName:'',
				gValue:''
			};
			var pSNode = _this.parentNode.getElementsByClassName('pic-selected');
			if(pSNode.length > 0){
				result.pValue = pSNode[0].dataset['value'];
				result.pName = pSNode[0].innerText;
			};
			if((_this.type == 2) || (_this.type == 3)||(_this.type == 4)){
				var cSNode = _this.childNode.getElementsByClassName('pic-selected');
				if(cSNode.length > 0){
					result.cValue = cSNode[0].dataset['value'];
					result.cName = cSNode[0].innerText;
				};
			};
			if(_this.type == 4){
				var gSNode = _this.grandNode.getElementsByClassName('pic-selected');
				if(gSNode.length > 0){
					result.gValue = gSNode[0].dataset['value'];
					result.gName = gSNode[0].innerText;
				};	
			};
			_this.removeListener();
			var mask = document.getElementById('pic-mask');
			if(mask){
				document.body.removeChild(mask);
			}else{
				document.body.removeChild(_this.target);
			};
			if(_this.opt.okEvent){
				_this.opt.okEvent.call(null,result);
			};
		},
		cancelEvent:function(ev){
			_this.removeListener();
			var mask = document.getElementById('pic-mask');
			if(mask){
				document.body.removeChild(mask);
			}else{
				document.body.removeChild(_this.target);
			};
			if(_this.opt.cancelEvent){
				_this.opt.cancelEvent.call(null);
			};
		}
	};
	_this.tochObj = tochObj;
	this.picCon.addEventListener('touchstart',tochObj.touchStart,false);
	this.picCon.addEventListener('touchmove',tochObj.touchMove,false);
	this.picCon.addEventListener('touchend',tochObj.touchEnd,false);
	this.target.getElementsByClassName('pic-ok')[0].addEventListener('click',tochObj.okEvent,false);
	this.target.getElementsByClassName('pic-cancel')[0].addEventListener('click',tochObj.cancelEvent,false);
};
/**
 * 
 * @param {Object} opt 可选参数，暂未开放，可以取消指定的Listener事件
 */
lcPicker.prototype.removeListener = function(opt){
	this.picCon.removeEventListener('touchstart',this.tochObj.touchStart);
	this.picCon.removeEventListener('touchmove',this.tochObj.touchMove);
	this.picCon.removeEventListener('touchend',this.tochObj.touchEnd);
	this.target.getElementsByClassName('pic-ok')[0].removeEventListener('click',this.tochObj.okEvent);
	this.target.getElementsByClassName('pic-cancel')[0].removeEventListener('click',this.tochObj.cancelEvent);
};
//设置父节点当前选中的Item显示
lcPicker.prototype.setPCurItem = function(flag){
	var transY = flag * this.itemHeight - this.originY;
	this.parentNode.style.webkitTransform = 'translate3d(0,'+(-transY)+'px,0)';
	this.parentNode.style.transform = 'translate3d(0,'+(-transY)+'px,0)';
	this.moveParam.curPY = -transY;
	var last = this.parentNode.getElementsByClassName('pic-selected');
	if(last.length > 0){
		last[0].className = 'p-item';
	};
	this.parentNode.getElementsByClassName('p-item')[flag].className = 'p-item pic-selected';
	this.selectedPItem = flag;
	
};
//设置子节点当前选中的item
lcPicker.prototype.setCCurItem = function(flagArr){
	var transY = flagArr[1] * this.itemHeight - this.originY;
	this.childNode.style.webkitTransform = 'translate3d(0,'+(-transY)+'px,0)';
	this.childNode.style.transform = 'translate3d(0,'+(-transY)+'px,0)';
	this.moveParam.curCY = -transY;
//	console.log(flagArr);
	var last = this.childNode.getElementsByClassName('pic-selected');
	if(last.length > 0){
		last[0].className = 'p-item';
	};
	this.childNode.getElementsByClassName('p-item')[flagArr[1]].className = 'p-item pic-selected';
	this.selectedCItem = flagArr[1];
};
//设置三级节点当前选中的item
lcPicker.prototype.setGCurItem = function(flagArr){
	var transY = flagArr[2] * this.itemHeight - this.originY;
	this.grandNode.style.webkitTransform = 'translate3d(0,'+(-transY)+'px,0)';
	this.grandNode.style.transform = 'translate3d(0,'+(-transY)+'px,0)';
	this.moveParam.curGY = -transY;
//	console.log(flagArr);
	var last = this.grandNode.getElementsByClassName('pic-selected');
	if(last.length > 0){
		last[0].className = 'p-item';
	};
	this.grandNode.getElementsByClassName('p-item')[flagArr[2]].className = 'p-item pic-selected';
	this.selectedGItem = flagArr[2];
};

